package top.usking.tools.log.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.StringJoiner;

/**
 * AOP log property.
 *
 * @author LiuShijin
 * @date 2022-01-28
 */
@ConfigurationProperties("top.usking.log")
public class AopLogProperties {
    private static final Logger LOGGER = LoggerFactory.getLogger(AopLogProperties.class);

    private boolean enabled = false;
    private String logPointcutExpression;

    public void setLogPointcutExpression(String logPointcutExpression) {
        if (isPointcutExpression(logPointcutExpression)) {
            this.logPointcutExpression = logPointcutExpression;
        } else {
            StringJoiner sj = new StringJoiner("||");
            Arrays.stream(logPointcutExpression.split(","))
                    .filter(f -> !"".equals(f.trim()))
                    .forEach(item -> sj.add(getPointcutExpression(item)));
            this.logPointcutExpression = sj.toString();
        }
        LOGGER.info("top.usking.log.default-pointcut-expression:[{}]", this.logPointcutExpression);
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public String getLogPointcutExpression() {
        return logPointcutExpression;
    }

    public boolean getEnabled() {
        return enabled;
    }

    private static String getPointcutExpression(String str) {
        return String.format("execution(public * %s(..))", str);
    }

    private static boolean isPointcutExpression(String str) {
        return str.trim().startsWith("execution(");
    }

    @Override
    public String toString() {
        return "AopLogProperties{" +
                "logPointcutExpression='" + logPointcutExpression + '\'' +
                ", enabled=" + enabled +
                '}';
    }

    @PostConstruct
    public void init() {
        LOGGER.info("AOP Log config:[{}]", this);
    }
}
